import { createServer } from 'http'
import express from 'express'
import expressWs from 'express-ws'
import { useTable } from '../utils/db'
import { TABLE } from '../utils/table'

const START_PORT = '3696'
const onlineUsers: { ws: any; key: string }[] = []

export async function wsSyncData(uKey: string) {
  console.log(`${uKey}发起转发，给${onlineUsers.length}个用户！`)
  const { data: list, count: total } = await useTable(TABLE.MAIN)
    .field('id,name')
    .where({ state: 1 })
    .order('sort')
    .page(CONF_DEFINE_PAGE, CONF_DEFINE_PAGESIZE)
    .countSelect()
  onlineUsers.forEach((client) => {
    const { ws, key } = client || {}
    ws && key !== uKey && ws.send(JSON.stringify({ list, total }))
  })
}

export default defineNitroPlugin(() => {
  const app = express()
  const server = createServer(app)
  expressWs(app, server)
  app.ws('/queue', function (ws: any) {
    ws.on('message', function (msg: string) {
      onlineUsers.push({ ws, key: msg })
    })
    ws.on('close', function () {
      const index = onlineUsers.findIndex(({ ws: e }) => e == ws)
      index !== -1 && onlineUsers.splice(index, 1)
    })
  })
  try {
    server.listen(START_PORT, () => {
      console.log(
        global.process.version,
        `ws服务器已运行: ws://127.0.0.1:${START_PORT}/queue`,
      )
    })
  } catch (e) {
    console.log('...')
  }
})
